package com.yami.shop.api.listener;

import com.yami.shop.bean.enums.UserFundDetailEnum;
import com.yami.shop.bean.event.ReceiptOrderEvent;
import com.yami.shop.bean.event.SubmitOrderEvent;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserFundDetail;
import com.yami.shop.bean.order.ReceiptOrderOrder;
import com.yami.shop.bean.order.SubmitOrderOrder;
import com.yami.shop.otherservice.OneLevelDistributionService;
import com.yami.shop.otherservice.ThreeLevelDistributionService;
import com.yami.shop.otherservice.UserLevelUpgradeService;
import com.yami.shop.otherservice.UserVipLevelUpgradeService;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.UserFundDetailService;
import com.yami.shop.service.UserService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component("defaultReceiptOrderListener")
@AllArgsConstructor
public class ReceiptOrderListener {

    @Autowired
    private OrderService orderService;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private UserService userService;

    @Autowired
    private UserFundDetailService userFundDetailService;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ThreeLevelDistributionService threeLevelDistributionService;

    @Autowired
    private UserVipLevelUpgradeService userVipLevelUpgradeService;

    @Autowired
    private UserLevelUpgradeService userLevelUpgradeService;

    @Autowired
    private OneLevelDistributionService oneLevelDistributionService;

    @EventListener(ReceiptOrderEvent.class)
    @Order(ReceiptOrderOrder.DEFAULT)
    public void defaultReceiptOrderListener(ReceiptOrderEvent event) {
        //订单收货成功

        //发送三级分销奖励(三级分销功能)(暂时停用)
        //threeLevelDistributionService.grantReward(String.valueOf(event.getOrder().getOrderId()));

        //下单用户自动升级vip等级(三级分销功能)(暂时停用)
        //userVipLevelUpgradeService.autoUpgradeAllHigherLevel(event.getOrder().getUserId());

        //用户第一次下单,奖励给推荐人,之后再次下单,给自己(一级分销功能)
        oneLevelDistributionService.referenceOrderAndRepeatOrderReward(event.getOrder().getUserId(),event.getOrder().getOrderNumber());
        //自动升级为普通会员(一级分销功能)
        userLevelUpgradeService.autoUpgrade(event.getOrder().getUserId());


        /*com.yami.shop.bean.model.Order byId = orderService.getById(event.getOrder().getOrderId());
        if(byId == null){
            throw new RuntimeException("订单收货成功 事件 查询订单为空");
        }

        System.out.println("收货成功");

        //下单用户
        User byId0 = userService.getById(byId.getUserId());

        if(byId0 == null){
            return;
        }

        String enableDistributionProdIds = this.getValueByConfig("enable_distribution_prod_ids");
        List<String> prodIds = Arrays.asList(StringUtils.split(enableDistributionProdIds, ","));

        List<OrderItem> oi = orderItemService.lambdaQuery().eq(OrderItem::getOrderNumber, byId.getOrderNumber()).list();
        List<String> collect = oi.stream().map(o -> o.getProdId()).map(p -> String.valueOf(p)).collect(Collectors.toList());

        //在用户下单的订单中,找是否存在开启分销的商品
        List<String> collect1 = collect.stream().filter(op -> prodIds.contains(op)).collect(Collectors.toList());

        if(!collect1.isEmpty()){
            //一级分销用户
            User byId1 = userService.getById(byId0.getHigherLevelUid());
            if(byId1 != null){
                String level1 = this.getValueByConfig("level1");

                BigDecimal distributionBonus = byId1.getDistributionBonus();

                if( distributionBonus == null){
                    distributionBonus = BigDecimal.ZERO;
                }

                BigDecimal add = distributionBonus.add(new BigDecimal(level1));

                User user = new User();
                user.setUserId(byId1.getUserId());
                user.setDistributionBonus(add);
                userService.updateById(user);

                UserFundDetail detail=new UserFundDetail();
                detail.setUserType("tz_user");
                detail.setUid(byId1.getUserId());
                detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                detail.setType(UserFundDetailEnum.TYPE_0.getValue());
                detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                detail.setMoney(new BigDecimal(level1));
                detail.setResidueMoney(add);
                detail.setTitle("一级分销奖励");
                detail.setDetails("一级分销奖励:"+level1 +", 剩余:"+add);
                detail.setDelFlag(0);

                //detail.setCreateBy(userId);
                detail.setCreateTime(new Date());

                userFundDetailService.save(detail);
            }

            //二级分销用户
            User byId2 = userService.getById(byId1.getHigherLevelUid());
            if(byId2 != null){
                String level1 = this.getValueByConfig("level2");

                BigDecimal distributionBonus = byId2.getDistributionBonus();

                if( distributionBonus == null){
                    distributionBonus = BigDecimal.ZERO;
                }

                BigDecimal add = distributionBonus.add(new BigDecimal(level1));

                User user = new User();
                user.setUserId(byId2.getUserId());
                user.setDistributionBonus(add);
                userService.updateById(user);

                UserFundDetail detail=new UserFundDetail();
                detail.setUserType("tz_user");
                detail.setUid(byId2.getUserId());
                detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                detail.setType(UserFundDetailEnum.TYPE_1.getValue());
                detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                detail.setMoney(new BigDecimal(level1));
                detail.setResidueMoney(add);
                detail.setTitle("二级分销奖励");
                detail.setDetails("二级分销奖励:"+level1 +", 剩余:"+add);
                detail.setDelFlag(0);

                //detail.setCreateBy(userId);
                detail.setCreateTime(new Date());

                userFundDetailService.save(detail);
            }

            //三级分销用户
            User byId3 = userService.getById(byId2.getHigherLevelUid());
            if(byId3 != null){
                String level1 = this.getValueByConfig("level3");

                BigDecimal distributionBonus = byId3.getDistributionBonus();

                if( distributionBonus == null){
                    distributionBonus = BigDecimal.ZERO;
                }

                BigDecimal add = distributionBonus.add(new BigDecimal(level1));

                User user = new User();
                user.setUserId(byId3.getUserId());
                user.setDistributionBonus(add);
                userService.updateById(user);

                UserFundDetail detail=new UserFundDetail();
                detail.setUserType("tz_user");
                detail.setUid(byId3.getUserId());
                detail.setCategory(UserFundDetailEnum.DISTRIBUTION_BONUS.getValue());
                detail.setType(UserFundDetailEnum.TYPE_2.getValue());
                detail.setPm(Integer.valueOf(UserFundDetailEnum.PM_1.getValue()));
                detail.setMoney(new BigDecimal(level1));
                detail.setResidueMoney(add);
                detail.setTitle("三级分销奖励");
                detail.setDetails("三级分销奖励:"+level1 +", 剩余:"+add);
                detail.setDelFlag(0);

                //detail.setCreateBy(userId);
                detail.setCreateTime(new Date());

                userFundDetailService.save(detail);
            }
        }*/
    }

    /**
     * 获取配置项
     * @param key
     * @return
     */
    public String  getValueByConfig(String key) {
        List<String> param_value = jdbcTemplate.query("select param_value from tz_sys_config where param_key = ? ", new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                return rs.getString("param_value");
            }
        }, key);

        if(param_value.isEmpty()){
            return null;
        }else{
            return param_value.get(0);
        }
    }
}
